<template>
	<view class="page-container">
		<view class="header">
			<text class="title">左侧栏管理</text>
			<text class="subtitle">长按拖动图标可排序</text>
			<view class="header-decoration"></view>
		</view>

		<view class="card-container">
			<view v-for="(item, index) in list" :key="index" class="card-item" :class="{
					'unsaved': !item._id,
					'dragging': dragIndex === index,
					'drag-over': dragOverIndex === index && dragIndex !== index
				}">
				<view class="card-content">
					<uni-icons class="drag-icon" type="bars" size="20" color="#A1A5B7"
						@touchstart="onTouchStart(index, $event)" @touchmove="onTouchMove(index, $event)"
						@touchend="onTouchEnd" @touchcancel="onTouchEnd"></uni-icons>
					<view class="card-title">
						排序{{ item.order }}
					</view>
					<view class="input-group">
						<text class="input-label">内容</text>
						<textarea class="content-textarea" v-model="item.content" :placeholder="`请输入内容`" auto-height />
					</view>
				</view>
				<view class="action-buttons">
					<button class="btn save-btn" @click="handleSubmit(index)" size="mini">
						<uni-icons type="checkmarkempty" size="16" color="#fff"></uni-icons>
						<text>保存</text>
					</button>
					<button class="btn delete-btn" @click="handleDel(index)" size="mini">
						<uni-icons type="trash" size="16" color="#fff"></uni-icons>
						<text>删除</text>
					</button>
				</view>
			</view>

			<view class="footer-actions">
				<button class="add-btn" @click="handleAdd">
					<uni-icons type="plusempty" size="18" color="#fff"></uni-icons>
					<text>新增数据</text>
				</button>
			</view>
		</view>

		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
		<ver />
	</view>
</template>

<script setup>
	import ver from '@/components/ver.vue'
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		getPrizeDescList,
		addPrizeDesc,
		updatePrizeDesc,
		deletePrizeDesc
	} from '@/api/prizeDesc.js';

	const list = ref([]);
	const message = ref();
	const msgType = ref('success');
	const messageText = ref('');

	// 拖拽相关状态
	const dragIndex = ref(-1);
	const dragOverIndex = ref(-1);
	const startY = ref(0);
	const dragging = ref(false);
	const itemHeight = ref(60); // 默认高度

	const showMessage = (type, text) => {
		msgType.value = type;
		messageText.value = text;
		message.value.open();
	};

	const onTouchStart = (index, event) => {
		startY.value = event.touches[0].clientY;
		dragIndex.value = index;
		dragging.value = false;

		// 获取项目高度
		const query = uni.createSelectorQuery();
		query.select('.card-item').boundingClientRect(res => {
			if (res) {
				itemHeight.value = res.height;
			}
		}).exec();
	};

	const onTouchMove = (index, event) => {
		if (dragIndex.value === -1) return;

		const currentY = event.touches[0].clientY;
		const deltaY = currentY - startY.value;

		// 移动超过一定距离才开始拖拽
		if (!dragging.value && Math.abs(deltaY) < 10) return;

		dragging.value = true;

		// 计算当前拖拽到的位置
		const newIndex = Math.round(index + deltaY / itemHeight.value);

		if (newIndex >= 0 && newIndex < list.value.length && newIndex !== dragOverIndex.value) {
			dragOverIndex.value = newIndex;
		}
	};

	const onTouchEnd = async () => {
		if (!dragging.value || dragIndex.value === -1 || dragOverIndex.value === -1 || dragIndex.value ===
			dragOverIndex.value) {
			resetDragState();
			return;
		}

		// 执行位置交换
		const movedItem = list.value[dragIndex.value];
		const targetItem = list.value[dragOverIndex.value];

		// 检查目标项是否已保存
		if (!targetItem._id) {
			showMessage('error', '请先保存目标项');
			resetDragState();
			return;
		}

		// 交换数组位置
		const newList = [...list.value];
		[newList[dragIndex.value], newList[dragOverIndex.value]] = [newList[dragOverIndex.value], newList[dragIndex
			.value]];

		// 更新order值
		const tempOrder = movedItem.order;
		movedItem.order = targetItem.order;
		targetItem.order = tempOrder;

		// 更新列表
		list.value = newList;

		// 更新数据库
		try {
			await Promise.all([
				updatePrizeDesc(movedItem._id, {
					order: movedItem.order
				}),
				updatePrizeDesc(targetItem._id, {
					order: targetItem.order
				})
			]);
			showMessage('success', '顺序已更新');
		} catch (error) {
			showMessage('error', error.message || '顺序更新失败');
			// 恢复原顺序
			const originalList = [...list.value];
			[originalList[dragIndex.value], originalList[dragOverIndex.value]] = [originalList[dragOverIndex
				.value], originalList[dragIndex.value]];
			movedItem.order = tempOrder;
			targetItem.order = movedItem.order;
			list.value = originalList;
		}

		resetDragState();
	};

	const resetDragState = () => {
		dragIndex.value = -1;
		dragOverIndex.value = -1;
		dragging.value = false;
		startY.value = 0;
	};

	const handleDel = async (index) => {
		const item = list.value[index];

		uni.showModal({
			title: '确认删除',
			content: '确定要删除此项吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						if (item._id) {
							await deletePrizeDesc(item._id);
						}
						list.value.splice(index, 1);
						showMessage('success', '删除成功');
					} catch (error) {
						showMessage('error', error.message || '删除失败');
					}
				}
			}
		});
	};

	const handleAdd = () => {
		const maxOrder = list.value.length > 0 ? Math.max(...list.value.map(item => item.order)) + 1 : 1;
		list.value.push({
			content: '',
			order: maxOrder,
			_id: null
		});
	};

	const handleSubmit = async (index) => {
		const item = list.value[index];

		try {
			if (item._id) {
				const {
					updated
				} = await updatePrizeDesc(item._id, {
					content: item.content,
					order: item.order
				});
				if (updated) {
					showMessage('success', '更新成功');
				}
			} else {
				const {
					id
				} = await addPrizeDesc({
					content: item.content,
					order: item.order
				});
				item._id = id;
				showMessage('success', '添加成功');
			}
		} catch (error) {
			showMessage('error', error.message || '操作失败');
		}
	};

	onMounted(async () => {
		try {
			const res = await getPrizeDescList();
			list.value = res.map((item, index) => ({
				content: item.content || '',
				order: item.order || index + 1,
				_id: item._id || null
			})).sort((a, b) => a.order - b.order);
		} catch (error) {
			showMessage('error', error.message || '加载失败');
		}
	});
</script>

<style lang="scss" scoped>
	.page-container {
		padding: 24rpx;
		background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
		min-height: 100vh;
		font-family: 'Arial', sans-serif;
	}

	.header {
		margin-bottom: 32rpx;
		padding: 24rpx;
		background: #ffffff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		position: relative;
		overflow: hidden;

		.title {
			font-size: 36rpx;
			font-weight: 600;
			color: #1a1a1a;
			display: block;
			margin-bottom: 8rpx;
			position: relative;
			z-index: 2;
		}

		.subtitle {
			font-size: 24rpx;
			color: #7a7a7a;
			position: relative;
			z-index: 2;
		}

		.header-decoration {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 8rpx;
			background: linear-gradient(90deg, #4CAF50 0%, #2196F3 100%);
		}
	}

	.card-container {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}

	.card-item {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 28rpx;
		box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
		border: 2rpx solid #e0e3eb;
		border-left-width: 6rpx;
		border-top-width: 6rpx;
		position: relative;

		&:hover {
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
		}

		&.unsaved {
			border-left: 6rpx solid #FFC107;
			background: linear-gradient(90deg, rgba(255, 193, 7, 0.05) 0%, #ffffff 10%);
		}

		&.dragging {
			transform: scale(1.03);
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
			opacity: 0.9;
			background: #f8f9fa;
			z-index: 10;
		}

		&.drag-over {
			border-top: 6rpx solid #4CAF50;
		}
	}

	.card-content {
		display: flex;
		align-items: flex-start;
		gap: 20rpx;
		margin-bottom: 24rpx;

		.drag-icon {
			flex-shrink: 0;
			padding: 16rpx;
			padding-left: 0;
			touch-action: none;
			cursor: move;
		}

		.card-title {
			flex-shrink: 0;
			height: 72rpx;
			line-height: 72rpx;
			font-size: 24rpx;
			color: #666666;
			touch-action: none;
			cursor: move;
		}
	}

	.input-group {
		flex: 1;
		display: flex;
		flex-direction: column;

		.input-label {
			font-size: 24rpx;
			color: #666;
			margin-bottom: 8rpx;
		}

		.order-text {
			background: #f8f9fa;
			border: 2rpx solid #e0e3eb;
			border-radius: 8rpx;
			padding: 16rpx 20rpx;
			font-size: 28rpx;
			color: #333;
			width: 120rpx;
		}

		textarea {
			background: #f8f9fa;
			border: 2rpx solid #e0e3eb;
			border-radius: 8rpx;
			padding: 16rpx 20rpx;
			font-size: 28rpx;
			color: #333;
			transition: all 0.2s;

			&:focus {
				border-color: #4CAF50;
				background: #fff;
				box-shadow: 0 0 0 2rpx rgba(76, 175, 80, 0.2);
			}
		}

		.content-textarea {
			flex: 1;
			min-height: 120rpx;
		}
	}

	.action-buttons {
		display: flex;
		justify-content: flex-end;
		gap: 16rpx;

		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 8rpx;
			padding: 0 24rpx;
			border-radius: 8rpx;
			font-size: 26rpx;
			font-weight: 500;
			transition: all 0.2s;

			&:active {
				transform: scale(0.96);
			}

			&.save-btn {
				background: linear-gradient(135deg, #4CAF50 0%, #81C784 100%);
				color: white;
			}

			&.delete-btn {
				background: linear-gradient(135deg, #F44336 0%, #E57373 100%);
				color: white;
			}
		}
	}

	.footer-actions {
		display: flex;
		justify-content: space-between;
		gap: 24rpx;

		button {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 10rpx;
			height: 88rpx;
			border-radius: 12rpx;
			font-size: 28rpx;
			font-weight: 500;
			transition: all 0.2s;

			&:active {
				transform: scale(0.98);
			}
		}

		.add-btn {
			background: linear-gradient(135deg, #2196F3 0%, #64B5F6 100%);
			color: white;
			box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.3);
		}

		.save-all-btn {
			background: linear-gradient(135deg, #673AB7 0%, #9575CD 100%);
			color: white;
			box-shadow: 0 4rpx 12rpx rgba(103, 58, 183, 0.3);
		}
	}

	@media (max-width: 768px) {
		.card-content {
			flex-wrap: wrap;

			.input-group {
				width: 100%;
			}
		}

		.action-buttons {
			justify-content: space-between;
		}
	}
</style>